/**
 * woon 20160712
 */
var deviceone = require("deviceone");
var nf = deviceone.sm("do_Notification");
var easemob = deviceone.sm("do_Easemob");
var app = deviceone.sm("do_App");
var global = deviceone.sm("do_Global");
var device = deviceone.sm("do_Device");
var audio = deviceone.sm("do_Audio");//音频播放与录制
var album = deviceone.sm("do_Album");
var open = require("helper/open");
var http = require("helper/http");
var imApi = require("helper/imApi");
var qqCacher = require("helper/qqCacher");
var httpSilence = require("helper/httpSilence");//没有等提示
var userUtil = require("helper/user");
var friendHelper = require("helper/friend");
var md5Helper = require("helper/md5");//转码（生产唯一码）
var imUrl = require("url/im");
var deviceUtil = require("helper/device");
var circleUrl = require("url/circle");

//本地缓存,存放im用户呢称(name)、头像(logo)、imId、userId
var imCache = deviceone.sm("do_DataCache");

var tryTimes = 0;
/**
 * 公开性：公开
 * 监听：im初始化一些监听
 */

function initIM(){
	easemob.on("connectionStateChanged", function(data, e) {
		//{state:0 登录成功后,手机无法上网时 | 1 登录成功后,网络状态变化时}
		if(data.state==0){
			deviceone.print("IM- 登录成功后,手机无法上网时!");
		}else if(data.state==1){
			deviceone.print("IM-登录成功后,网络状态变化!");
		}
	});
	easemob.on("logout", function(data, e) {
		//说明 :	被动退出登录：1. 正在登录的账号在另一台设备上登录；2. 正在登录的账号被从服务器端删除。主动调用退出方法不会触发
		//返回值描述 :{state:0 显示帐号已经被移除 | 1 显示帐号在其他设备登陆}
		if(data.state==0){
			deviceone.print("IM-帐号已经被移除!");
			nf.toast("你的im账户已经被移除");
		}else if(data.state==1){
			deviceone.print("IM-帐号在其他设备登陆!");
			if(qqCacher.isFromStartup()==="1"){
				loginIM();
				qqCacher.isFromStartup("2");
			}else{
				if(userUtil.loginToken()!==""){
					userUtil.loginToken("");
					imApi.logoutIM(function(){
						app.fire("fireUserLogout");
						nf.toast("请重新登录");
					});
				}else{
					imApi.logoutIM();
				}
			}
		}
	});
	 
	//订阅autoLogin事件，获取自动登录状态
	easemob.on("autoLogin",function(data,e){
		//说明 :	若登录时设置自动登录，则下次进入自动登录时触发
		deviceone.print(JSON.stringify(data),"IM自动登录成功");
		addMsgListener();
	})
}

function addMsgListener(){
	//deviceone.print("IM...addMsgListener","");
	easemob.off("messages");//防止多次监听
	easemob.on("messages", function(data, e) {
		//deviceone.print("IM...new message come in","");
		addUnReadMsgCount(data);//收到消息时，处理我的未读消息数量【含群聊、单聊、总的未读数量】
		playRingBeer4Message(data);//处理新消息--声音提醒【含非扰模式】
		app.fire("im_comming_messages4msg", data);//IM收到新的消息--消息页面
		app.fire("im_comming_messages4chat", data);//IM收到新的消息--单聊页面
		app.fire("im_comming_messages4gchat", data);//IM收到新的消息--群聊页面
		app.fire("qq_fire_show_msg_tip");//显示消息 红点【右上角消息图标】
	});
}

/**
 * 处理 未读消息数量
 * @param message
 * 【私有方法】
 */
function addUnReadMsgCount(message) {
	increaseMyUnReadCount();//增加【我的未读消息数量】
	if(message.chatType == "Chat"){
		increaseUnReadCount2Her({herId:message.from});//她发给我的未读消息数量+1
	}else if(message.chatType == "GroupChat"){
		increaseUnReadCount2Her({herId:message.to});//群聊未读消息数量+1
	}
}

/**
 * 处理新消息--声音提醒【含非扰模式】
 * @param message
 * 【私有方法】
 */
function playRingBeer4Message(message) {
	if(message.chatType == "Chat"){
		alertNewMsg();//目前单聊设置播放和震动，群聊需要设置权限由用户决定是否针对和声音提醒
	}else if(message.chatType == "GroupChat"){//群聊
		if(cacheMsgSilence(message.to)!="1"){
			//如果对这个群聊，用户没有设置“消息免打扰”，就响铃/振动
			alertNewMsg();
		}
	}
}
/***********************************用户缓存 begin**************************************/
var cacheByImId = "im_imid_";//IM用户缓存key头部(imId主键)
var cacheByUserId = "im_userid_";//IM用户缓存key头部(userId主键)

/**
 * 公开性：内部
 * 保存im用户到本地缓存(用户)
 * @param imUser
 * 		{imId:aaa, userId:bbb, name:ccc, logo:"http://...ddd.png"}
 */
function cacheUser(imUser){
	if(imUser!=null && imUser!="undefined" && imUser.imId != null && imUser.imId!=""){
		imCache.saveData({key: cacheByImId+""+imUser.imId, value: imUser});
	}
	if(imUser!=null && imUser!="undefined" && imUser.userId != null && imUser.userId!=""){
		imCache.saveData({key: cacheByUserId+""+imUser.userId, value: imUser});
	}
}
/**
 * 公开性：公开
 * 从本地缓存取im对象(用户)-主键imId
 * @param imId
 * @returns imUser {imId:aaa, userId:bbb, name:ccc, logo:"http://...ddd.png"}
 */
function loadUserByImId(imId,callBack){
	if(imId!=null && imId!="undefined" && imId!=""){
		var imUser = imCache.loadData({key: cacheByImId+""+imId});
		if (imUser) {//如果本地缓存能找到,反回本地对象			
			if(imUser.logo && imUser.logo.indexOf("@")<0){
				//如果本地缓存中的头象是原图，刷新一下缓存
				reflashCacheUser(imUser.userId);
		    }
			if(callBack && callBack!=null && callBack!="undefined"){
				callBack(imUser);
			}
		    
		} else {//先查后到数据库,再缓存到本地
			httpSilence.post(imUrl.url.user.getImUser, {imId:imId}, function(data) {
				var imDbUser = data.imUser;
				if (imDbUser) {
					imUser = {
							imId:imDbUser.imId, 
							userId:imDbUser.userId, 
							name:imDbUser.imNickName, 
							logo:imDbUser.fullLogo	
					};
					cacheUser(imUser);//缓存到本地
					if(callBack && callBack!=null && callBack!="undefined"){
						callBack(imUser);
					}
				}
			});
		}
	}else{
		if(callBack && callBack!=null && callBack!="undefined"){
			callBack({});
		}
	}
}

/**
 * 公开性：公开
 * 从本地缓存取im对象(用户)-主键userId
 * @param userId
 * @returns imUser {imId:aaa, userId:bbb, name:ccc, logo:"http://...ddd.png"}
 */
function loadUserByUserId(userId,callBack){
	if(userId!=null && userId!="undefined" && userId!=""){
		var imUser = imCache.loadData({key: cacheByUserId+""+userId});
		if (imUser) {//如果本地缓存能找到,反回本地对象
			if(imUser.logo && imUser.logo.indexOf("@")<0){
				//如果本地缓存中的头象是原图，刷新一下缓存
				reflashCacheUser(imUser.userId);
		    }
		    if(callBack && callBack!=null && callBack!="undefined"){
				callBack(imUser);
			}
		} else {//先查后到数据库,再缓存到本地
			httpSilence.post(imUrl.url.user.getImUser, {userId:userId}, function(data) {
				var imDbUser = data.imUser;
				if (imDbUser) {
					imUser = {
							imId:imDbUser.imId, 
							userId:imDbUser.userId, 
							name:imDbUser.imNickName, 
							logo:imDbUser.fullLogo	
					};
					cacheUser(imUser);//缓存到本地
					if(callBack && callBack!=null && callBack!="undefined"){
						callBack(imUser);
					}
				}
			});
		}
	}else{
		if(callBack && callBack!=null && callBack!="undefined"){
			callBack({});
		}
	}
}

/**
 * 从数据库里查询用户并更新缓存
 * @param userId
 * @param callBack
 */
function reflashCacheUser(userId,callBack){
	if(userId!=null && userId!="undefined" && userId!=""){
		//先查后到数据库,再缓存到本地
		httpSilence.post(imUrl.url.user.getImUser, {userId:userId}, function(data) {
			var imDbUser = data.imUser;
			if (imDbUser) {
				var imUser = {
						imId:imDbUser.imId, 
						userId:imDbUser.userId, 
						name:imDbUser.imNickName, 
						logo:imDbUser.fullLogo	
				};
				cacheUser(imUser);//缓存到本地
				if(callBack && callBack!=null && callBack!="undefined"){
					callBack(imUser);
				}
			}
		});
	}else{
		if(callBack && callBack!=null && callBack!="undefined"){
			callBack({});
		}
	}
}
/***********************************用户缓存 end**************************************/

/***********************************群组缓存 begin**************************************/
var cacheByImGroupId = "qquan2_im_imgroupid_";//IM群组缓存key头部(imGroupId主键)
var cacheByGroupId = "qquan2_im_groupid_";//IM群组缓存key头部(groupId主键)
/**
 * 公开性：内部
 * 保存im群组到本地缓存(群组)
 * @param imGroup
 * 		{imId:aaa, groupId:bbb, name:ccc, logo:"http://...ddd.png"}
 */
function cacheGroup(imGroup){
	if(imGroup!=null && imGroup!="undefined" && imGroup.imId != null && imGroup.imId!=""){
		imCache.saveData({key: cacheByImGroupId+""+imGroup.imId, value: imGroup});
	}
	if(imGroup!=null && imGroup!="undefined" && imGroup.groupId != null && imGroup.groupId!=""){
		imCache.saveData({key: cacheByGroupId+""+imGroup.groupId, value: imGroup});
	}
}
/**
 * 公开性：公开
 * 从本地缓存取im对象(群组)-主键imId
 * @param imId
 * @returns imGroup {imId:aaa, groupId:bbb, name:ccc, logo:"http://...ddd.png"}
 */
function loadGroupByImId(imId,callBack){
	if(imId!=null && imId!="undefined" && imId!=""){
		var imGroup = imCache.loadData({key: cacheByImGroupId+""+imId});
		if (imGroup) {//如果本地缓存能找到,反回本地对象
		    if(callBack && callBack!=null && callBack!="undefined"){
				callBack(imGroup);
			}
		} else {//先查后到数据库,再缓存到本地
			httpSilence.post(imUrl.url.group.getImGroup, {imGroupId:imId}, function(data) {
				var imDbGroup = data.imGroup;
				if (imDbGroup) {
					imGroup = {
							imId:imDbGroup.imGroupId, 
							groupId:imDbGroup.groupId, 
							name:imDbGroup.name, 
							logo:imDbGroup.fullLogo,
							imgItems:imDbGroup.imgItems,
							isCircle:imDbGroup.isCircle	
					};
					cacheGroup(imGroup);//缓存到本地
					if(callBack && callBack!=null && callBack!="undefined"){
						callBack(imGroup);
					}
				}
			});
		}
	}else{
		if(callBack && callBack!=null && callBack!="undefined"){
			callBack({});
		}
	}
}

/**
 * 公开性：公开
 * 从本地缓存取im对象(群组)-主键imId
 * @param imId
 * @returns imGroup {imId:aaa, groupId:bbb, name:ccc, logo:"http://...ddd.png"}
 */
function loadGroupByGroupId(groupId,callBack){
	if(groupId!=null && groupId!="undefined" && groupId!=""){
		var imGroup = imCache.loadData({key: cacheByGroupId+""+groupId});
		if (imGroup) {//如果本地缓存能找到,反回本地对象
		    if(callBack && callBack!=null && callBack!="undefined"){
				callBack(imGroup);
			}
		} else {//先查后到数据库,再缓存到本地
			httpSilence.post(imUrl.url.group.getImGroup, {groupId:groupId}, function(data) {
				var imDbGroup = data.imGroup;
				if (imDbGroup) {
					imGroup = {
							imId:imDbGroup.imGroupId, 
							groupId:imDbGroup.groupId, 
							name:imDbGroup.name, 
							logo:imDbGroup.fullLogo,
							imgItems:imDbGroup.imgItems,
							isCircle:imDbGroup.isCircle
							
					};
					cacheGroup(imGroup);//缓存到本地
					if(callBack && callBack!=null && callBack!="undefined"){
						callBack(imGroup);
					}
				}
			});
		}
	}else{
		if(callBack && callBack!=null && callBack!="undefined"){
			callBack({});
		}
	}
}

/**
 * 从数据库里查询群组并更新缓存
 * @param groupId
 * @param callBack
 */
function reflashCacheGroup(groupId,callBack){
	if(groupId!=null && groupId!="undefined" && groupId!=""){
		//先查后到数据库,再缓存到本地
		httpSilence.post(imUrl.url.group.getImGroup, {groupId:groupId}, function(data) {
			var imDbGroup = data.imGroup;
			if (imDbGroup) {
				var imGroup = {
						imId:imDbGroup.imGroupId, 
						groupId:imDbGroup.groupId, 
						name:imDbGroup.name, 
						logo:imDbGroup.fullLogo,
						imgItems:imDbGroup.imgItems,
						isCircle:imDbGroup.isCircle	
				};
				cacheGroup(imGroup);//缓存到本地
				if(callBack && callBack!=null && callBack!="undefined"){
					callBack(imGroup);
				}
			}
		});
	}else{
		if(callBack && callBack!=null && callBack!="undefined"){
			callBack({});
		}
	}
}
/***********************************群组缓存 end**************************************/

/***********************************我的IM用户信息缓存 begin**************************************/
var cacheMeImUserKey = "im_me_qquan_imid_@wo#";//我的IM用户缓存key

/**
 * 公开性：内部
 * 保存im用户到本地缓存(用户)
 * @param imUser
 * 		{imId:aaa, userId:bbb, name:ccc, logo:"http://...ddd.png"}
 */
function cacheMe(imUser){
	if(imUser!=null && imUser!="undefined"){
		imCache.saveData({key: cacheMeImUserKey, value: imUser});
	}
}

/**
 * 从数据库里查询我的信息并更新缓存
 * @param callBack
 */
function reflashCacheMe(callBack){
	//先查后到数据库,再缓存到本地
	httpSilence.post(imUrl.url.user.getMyImUser, {}, function(data) {
		var imDbUser = data.myImUser;
		if (imDbUser) {
			imUser = {
					imId:imDbUser.imId, 
					userId:imDbUser.userId, 
					name:imDbUser.imNickName, 
					logo:imDbUser.fullLogo,
					passWord:imDbUser.imPassWord
			};
			cacheMe(imUser);//缓存到本地
			if(callBack && callBack!=null && callBack!="undefined"){
				callBack(imUser);
			}
		}
	});
}

/**
 * 公开性：公开
 * 从本地缓存取im对象(用户)
 * @param callBack
 * @returns imUser {imId:aaa, userId:bbb, name:ccc, logo:"http://...ddd.png"}
 */
function loadMe(callBack){
		var imUser = imCache.loadData({key: cacheMeImUserKey});
		if (imUser) {//如果本地缓存能找到,反回本地对象
		    if(callBack && callBack!=null && callBack!="undefined"){
				callBack(imUser);
			}
		} else {//先查后到数据库,再缓存到本地
			httpSilence.post(imUrl.url.user.getMyImUser, {}, function(data) {
				var imDbUser = data.myImUser;
				if (imDbUser) {
					imUser = {
							imId:imDbUser.imId, 
							userId:imDbUser.userId, 
							name:imDbUser.imNickName, 
							logo:imDbUser.fullLogo,
							passWord:imDbUser.imPassWord
					};
					cacheMe(imUser);//缓存到本地
					if(callBack && callBack!=null && callBack!="undefined"){
						callBack(imUser);
					}
				}
			});
		}
}

/***********************************我的IM用户信息缓存 end**************************************/
function toChat(userId){
	if(userUtil.loginToken()===""){
		nf.toast("您还没有登陆哦.");
		return;
	}
	if(userId==null || userId=="" || userId=="undefined"){
		nf.toast("对方用户id为空.");
		return;
	}
	if(userUtil.userId() == userId){
		nf.toast("不能跟自己聊天.");
		return;
	}
	/*
	friendHelper.isMyFriend(userId,function(data){//聊天之前判断是否好友关系
		open.open("source://view/im/chat/chat.ui",{userId:userId});
	});
	*/
	open.open("source://view/im/chat/chat.ui",{userId:userId});
	
	
}

function toGroupChat(groupId){
	if(userUtil.loginToken()===""){
		nf.toast("您还没有登陆哦.");
		return;
	}
	if(groupId==null || groupId=="" || groupId=="undefined"){
		nf.toast("群组id为空");
		return;
	}
	var userId = userUtil.userId();
	if(userId !="" && userId!=null){
		httpSilence.post(circleUrl.url.member.isCircleMember, {circleId:groupId,memberId:userId}, function(data) {
			var isMember = data.isMember;
			if (isMember) {
				open.open("source://view/im/chat/gchat.ui",{groupId:groupId});	
			}else{
				nf.toast("您不是这个群聊的成员!");
			}
		});
	}
}

function toGroupMember(groupId){
	if(groupId==null || groupId=="" || groupId=="undefined"){
		nf.toast("群聊id为空");
		return;
	}
	reflashCacheGroup(groupId);//重新缓存圈子或群聊
	httpSilence.post(circleUrl.url.base.isGroupChat, {id:groupId}, function(data) {
		var isGroupChat = data.isGroupChat;
		if (isGroupChat) {
			open.open("source://view/circle/gchat/member/gchatMembers.ui",{circleId:groupId});//群聊-成员列表
		}else{
			open.open("source://view/circle/member/circleMembers.ui",{circleId:groupId});//圈子-成员列表
		}
		
	});
}

//登陆IM
//登陆IM
function loginIM(_callBack) {
	if(userUtil.loginToken()===""){
		nf.toast("您还没有登陆哦.");
		if(_callBack && _callBack!=null && _callBack!="undefined"){
			_callBack();
		}
	}else{
		httpSilence.post(imUrl.url.user.getMyImUser, {}, function(data) {
			var myImUser = data.myImUser;
			var isEnableIosChat = data.isEnableIosChat;
			if (myImUser) {
				var imUser = {
					imId:myImUser.imId, 
					userId:myImUser.userId, 
					name:myImUser.imNickName, 
					logo:myImUser.fullLogo,
					passWord:myImUser.imPassWord
				};
				cacheMe(imUser);//缓存到本地
				var isAutoLogin = false;//是否自动登陆
				if(deviceUtil.getOsType()=="2"){//IOS自动登陆
					//isAutoLogin = true;
				}
				if(deviceUtil.getOsType()=="2"){//苹果则判断是否要登录im
					if(isEnableIosChat&&isEnableIosChat=="1"){
						easemob.login({username : myImUser.imId,password : myImUser.imPassWord,autoLogin: isAutoLogin}, function(data, e) {
							if (data.state == 0) {
								addMsgListener();//监听消息
								app.fire("im_login_sucess");
								deviceone.print("IM登录成功",myImUser.imNickName);
								tryTimes = 0;
								if(_callBack && _callBack!=null && _callBack!="undefined"){
									_callBack();
								}
							} else if (data.state == 1) {
								deviceone.print("IM登录失败：" + data.message);
								tryTimes = tryTimes + 1;
								if(tryTimes<10){
									if(_callBack && _callBack!=null && _callBack!="undefined"){
										loginIM(_callBack());
									}else{
										loginIM();
									}
								}else{
									if(_callBack && _callBack!=null && _callBack!="undefined"){
										_callBack();
									}
								}
							}else{
								if(_callBack && _callBack!=null && _callBack!="undefined"){
									_callBack();
								}
							}
						});
					}else{
						if(_callBack && _callBack!=null && _callBack!="undefined"){
							_callBack();
						}
					}
				}else{
					easemob.login({username : myImUser.imId,password : myImUser.imPassWord,autoLogin: isAutoLogin}, function(data, e) {
						//deviceone.print(JSON.stringify(data),"IM登录返回：");
						if (data.state == 0) {
							addMsgListener();//监听消息
							app.fire("im_login_sucess");
							deviceone.print("IM登录成功",myImUser.imNickName);
							tryTimes = 0;
							if(_callBack && _callBack!=null && _callBack!="undefined"){
								_callBack();
							}
						} else if (data.state == 1) {
							deviceone.print("IM登录失败：" + data.message);
							tryTimes = tryTimes + 1;
							if(tryTimes<10){
								if(_callBack && _callBack!=null && _callBack!="undefined"){
									loginIM(_callBack());
								}else{
									loginIM();
								}
							}else{
								if(_callBack && _callBack!=null && _callBack!="undefined"){
									_callBack();
								}
							}
						}else{
							if(_callBack && _callBack!=null && _callBack!="undefined"){
								_callBack();
							}
						}
					});
				}
			}else{
				if(_callBack && _callBack!=null && _callBack!="undefined"){
					_callBack();
				}
			}
		});
	}
};

//保存未读消息ID
function storeUnReadAudioIds(msgId){
	var newAudioIds = imCache.loadData({key: "qquan_im_newAudioIds"});
	if(newAudioIds == null){
		newAudioIds = msgId+',';
		imCache.saveData({key: "qquan_im_newAudioIds", value: newAudioIds});
	}else{
		newAudioIds = newAudioIds.replace(msgId+',','')+msgId+',';
		imCache.saveData({key: "qquan_im_newAudioIds", value: newAudioIds});
	}
}
//去掉已读消息ID
 function removeReadedAudioId(msgId){
	var newAudioIds = imCache.loadData({key: "qquan_im_newAudioIds"});
	if(newAudioIds != null){
		newAudioIds = newAudioIds.replace(msgId+',','');
		imCache.saveData({key: "qquan_im_newAudioIds", value: newAudioIds});
	}
	
}
//是否新消息ID
 function isUnReadAudio(msgId){
	var newAudioIds = imCache.loadData({key: "qquan_im_newAudioIds"});
	if(newAudioIds == null){
		return false;
	}else{				
		if(newAudioIds.indexOf(msgId)>-1){
			return true;
		}else{
			return false;
		}
	}			
}

/**
 * 取得语音文件的本地路径
 * 如果文件没有下载过，就下载并返回本地路径
 * 如果以前下载过，就返回本地路径
 * @param audioRemotePath
 */
function loadAudioFile(audioRemotePath,callBack){
	if(audioRemotePath.indexOf("data://") > -1){
		//如果已经是本地路径，直接返回
		if(callBack && typeof callBack == "function"){
			callBack(audioRemotePath);
		}
	}else{
		//用md5方式生成一个唯一码，作为缓存的key,并且用作语音文件本地路径的一部份
		var localMD5key = md5Helper.MD5(audioRemotePath);
		var localPath = imCache.loadData({key: localMD5key});
		//从缓存中取语音本地路径,如果存在，表示已下载到本到
		//如果没有找到，表示没有下载过
		if(localPath){
			if(callBack && typeof callBack == "function"){
				callBack(localPath);
			}
		}else{
			//下载语音文件
			var targetLocalPath = "data://"+localMD5key+".amr";
			downloadAudio(audioRemotePath,targetLocalPath,function(data){
				//下载完成后，把localPath 存放到缓存中，表示已经下载到本地了
				imCache.saveData({key: localMD5key, value: targetLocalPath});
				if(callBack && typeof callBack == "function"){
					callBack(targetLocalPath);
				}
			})
		}
	}
}

//下载语音文件
function downloadAudio(source,target,callback){
	var http4down = deviceone.mm("do_Http");
	http4down.timeout = 16000;//16秒
	http4down.contentType = "application/json";
	http4down.url = source;
	http4down.on("success", function(data) {
    	if(callback && typeof callback == "function") {
            callback(target);
        }
	});
	http4down.on("fail", function(data) {
	    nf.toast("请检查网络或手机空间后再重试...")
	});
	http4down.on("progress", function(data) {
	});
	http4down.download(target);
};

//下载图片
function downloadImage(source,callback){
	if(source.indexOf("data://") > -1){
		nf.toast("图片保存至"+source);
		return;
	}
	var imgName = "qquan_img_" +new Date().getTime()+".jpg";
	var target = "data://"+imgName;
	var http4down = deviceone.mm("do_Http");
	http4down.timeout = 16000;//16秒
	http4down.contentType = "application/json";
	http4down.url = source;
	http4down.on("success", function(data) {
    	if(callback && typeof callback == "function") {
            callback(target);
        }else{
        	var imgName2 = "img_" +new Date().getTime()+".jpg"
        	album.save({path:target, name:imgName2,quality:100}, function(data, e) {
        	    nf.toast("图片已保存至"+target);
        	})
        }
	});
	http4down.on("fail", function(data) {
	    nf.toast("图片下载失败,请稍候再试!")
	});
	http4down.on("progress", function(data) {
	});
	http4down.download(target);
};

/**
 * 我跟她的聊天--未读消息数量+1【针对聊天对象】
 * arguments：paramJson {myId:myId,herId:herId,addCount:addCount}
 */
var im_me2herUnreadCountKey  =  "im_me2her_unread_countKey";
function increaseUnReadCount2Her(paramJson){
	if(paramJson){
		var myId = paramJson.myId;
		var herId = paramJson.herId;
		var increaseCount = 1;//默认+1
		if(paramJson.addCount){
			increaseCount = paramJson.addCount;
		}
		if(!myId || myId=="" || myId =="undefined"){
			myId = userUtil.userId();
		}
		if(herId!="" && herId!="undefined"){
			var cacheKey = im_me2herUnreadCountKey+myId+herId;
			if(imCache.hasData(cacheKey)){
				var value = imCache.loadData(cacheKey);
				if(!value || value==null || value=="undefined"){
					imCache.saveData({key: cacheKey, value: increaseCount});
				}else{
					imCache.saveData({key: cacheKey, value: parseInt(value)+increaseCount});
				}
			}else{
				imCache.saveData({key: cacheKey, value: increaseCount});
			}
		}
	}
};

/**
 * 我跟她的聊天--未读消息数量【清零】
 * arguments：paramJson {myId:myId,herId:herId}
 */
function clearUnReadCount2Her(paramJson){
	if(paramJson){
		var myId = paramJson.myId;
		var herId = paramJson.herId;
		if(!myId || myId=="" || myId =="undefined"){
			myId = userUtil.userId();
		}
		if(herId!="" && herId!="undefined"){
			imCache.saveData({key: im_me2herUnreadCountKey+myId+herId, value: 0});
		}
	}
};

/**
 * 我跟她的聊天--未读消息数量【查询】
 * arguments：paramJson {myId:myId,herId:herId}
 */
function getUnReadCount2Her(paramJson){
	if(userUtil.loginToken()===""){
		return 0;
	}
	if(paramJson){
		var myId = paramJson.myId;
		var herId = paramJson.herId;
		if(!myId || myId=="" || myId =="undefined"){
			myId = userUtil.userId();
		}
		if(herId!="" && herId!="undefined"){
			var cacheKey = im_me2herUnreadCountKey+myId+herId;
			if(imCache.hasData(cacheKey)){
				var value = imCache.loadData(cacheKey);
				return (!value || value==null || value=="undefined") ? 0 : parseInt(value);
			}else{
				return 0;
			}
		}else{
			return 0;
		}
	}else{
		return 0;
	}
};

/**
 * 存取“是否静音”
 * 1:静音;2:响铃/振动
 */
var imMsgSilenceKey = "im_msg_silence_key";
function cacheMsgSilence(){
	if(arguments.length==1){
		var imId = arguments[0];//对话im用户id或群组id
		if(imCache.hasData(imMsgSilenceKey+""+imId)){
			var value = imCache.loadData(imMsgSilenceKey+""+imId);
			if(!value || value==null || value==="undefined"){
				imCache.saveData(imMsgSilenceKey+""+imId,"2");
				return "2";//默认2-不静音
			}else{
				return value;
			}
		}else{
			imCache.saveData(imMsgSilenceKey+""+imId,"2");
			return "2";//默认2-不静音
		}
    }else if(arguments.length == 2){
    	var imId = arguments[0];
    	var isSilence = arguments[1];
    	if(isSilence=="1"){
    		imCache.saveData(imMsgSilenceKey+""+imId,"1");
    	}else{
    		imCache.saveData(imMsgSilenceKey+""+imId,"2");
    	}
    }else{
		return "2";//默认2-不静音
    }
};

/**
 * 新消息提醒（3种方式）
 *  1:静音;2:响铃;3：振动
 */
function alertNewMsg(){
	if(global.getMemory("imLastBeepTime") !="" && global.getMemory("imLastBeepTime") != null){
		if((global.getTime() - global.getMemory("imLastBeepTime")) < 2000){
			return;//如果现在距离上一次响铃不到2秒，不执行响铃
		}
	}
	global.setMemory("imLastBeepTime",global.getTime());
	device.vibrate({duration:150});
	device.beep();
};

/**
 * 发送语音后“嗖”一声
 * @returns
 */
function playXiu(){
	audio.play("source://view/im/chat/audio/xiu.mp3");
};

//我的未读消息数量【+1】
var myUnReadMsgCountKey  =  "my_unread_message_key@qquan";
function increaseMyUnReadCount(paramJson){
	var increaseCount = 1;//默认+1
	var myId = "";
	if(paramJson){
		myId = paramJson.myId;
		if(paramJson.addCount){
			increaseCount = paramJson.addCount;
		}
	}
	if(!myId || myId=="" || myId =="undefined"){
		myId = userUtil.userId();
	}
	var cacheKey = myUnReadMsgCountKey+myId;
	if(imCache.hasData(cacheKey)){
		var value = imCache.loadData(cacheKey);
		if(!value || value==null || value=="undefined"){
			imCache.saveData({key: cacheKey, value: increaseCount});
		}else{
			imCache.saveData({key: cacheKey, value: parseInt(value)+increaseCount});
		}
	}else{
		imCache.saveData({key: cacheKey, value: increaseCount});
	}
	
};

/**
 * 减少我的未读消息数量
 * @param reduceCount 减量
 * @returns
 */
function reduceMyUnReadCount(paramJson){
	if(userUtil.loginToken()===""){
		return;
	}
	if(paramJson){
		var myId = paramJson.myId;
		if(!myId || myId=="" || myId =="undefined"){
			myId = userUtil.userId();
		}
		if(paramJson.reduceCount){
			var reduceCount = paramJson.reduceCount;
			if(!reduceCount || reduceCount==null || reduceCount=="undefined" || isNaN(reduceCount)){
				return;
			}
			if(parseInt(reduceCount) <= 0){
				return;
			}
			var cacheKey = myUnReadMsgCountKey+myId;
			if(imCache.hasData(cacheKey)){
				var value = imCache.loadData(cacheKey);
				if(!value || value==null || value=="undefined"){
					imCache.saveData({key: cacheKey, value: 0});
				}else{
					if(parseInt(value) <= parseInt(reduceCount)){
						imCache.saveData({key: cacheKey, value: 0});
					}else{
						imCache.saveData({key: cacheKey, value: parseInt(value)-parseInt(reduceCount)});
					}
				}
			}else{
				imCache.saveData({key: cacheKey, value: 0});
			}
		}
	}
};

//我的未读消息总数【清零】
function clearMyUnReadCount(paramJson){
	var myId = "";
	if(paramJson){
		myId = paramJson.myId;
	}
	if(!myId || myId=="" || myId =="undefined"){
		myId = userUtil.userId();
	}
	imCache.saveData({key: myUnReadMsgCountKey+myId, value: 0});
};
//我的未读消息总数【查询】
function getMyUnReadCount(paramJson){
	if(userUtil.loginToken()===""){
		return 0;
	}
	var myId = "";
	if(paramJson){
		myId = paramJson.myId;
	}
	if(!myId || myId=="" || myId =="undefined"){
		myId = userUtil.userId();
	}
	if(imCache.hasData(myUnReadMsgCountKey+myId)){
		var value = imCache.loadData(myUnReadMsgCountKey+myId);
		return (!value || value==null || value=="undefined") ? 0: parseInt(value);
	}else{
		return 0;
	}
};

//与在线客服聊天
function chat2OnlineService(){
	if(userUtil.loginToken()===""){
		nf.toast("您还没有登陆哦.");
		return;
	}
	httpSilence.post(imUrl.url.user.getImOnlineService, {}, function(data) {
		var imOnlineService = data.imOnlineService;
		if (imOnlineService) {
			var userId = imOnlineService.id;
			if(userUtil.userId() == userId){
				nf.toast("不能跟自己聊天.");
				return;
			}else{
				open.open("source://view/im/chat/chat.ui",{userId:userId});
			}
		}
	});
}
/**
 * 发送群聊邀请提醒【"XXX"邀请你加入群聊】
 * @param groupId 【圈子ID\群聊id(非imid)】
 * @param txtMessage 【文本内容】
 * @returns
 */
function sendGroupChatTip(groupId,txtMessage) {
	if(userUtil.loginToken()===""){
		nf.toast("您还没有登陆哦.");
		return;
	}
	loadGroupByGroupId(groupId,function(imGroup){
		var groupImId = imGroup.imId;
		easemob.sendTextMessage({
			username : groupImId,
			text : txtMessage,
			chatType : "GroupChat"
		}, function(data, e) {
			deviceone.print(txtMessage,"发送群聊消息");
		});
	})
}

//获取所有未读消息数量【andriod专用】
function cacheUnreadMsgCount4Andriod(){
	if(deviceUtil.getOsType()!="1"){//1-android;2-ios;3-window 
		return;
	}
	easemob.getAllConversations(function(data, e) {
		if(data.length==0){
			return;
		}
		for (var i = 0; i < data.length; i++) {
			addUnreadMsgCount4Chater(data[i].conversationId,data[i].type);
		}
	})
}

//获取所有未读消息数量【andriod专用】
function addUnreadMsgCount4Chater(vsonversationId,vsChatType){
	easemob.unreadMessagesCount({conversationId:vsonversationId,chatType:vsChatType},function(unReadCount){
		if(unReadCount>0){
			app.fire("qq_fire_show_msg_tip");//消息红点
			increaseUnReadCount2Her({herId:vsonversationId,addCount:unReadCount});//我与他或群聊的未读消息数量+unReadCount
			increaseMyUnReadCount({addCount:unReadCount});//我的未读消息总+unReadCount
		}
	})
}

//卖家收新订单提醒
function playOrderTip4Seller(){
	audio.play("source://view/im/chat/audio/newOrder.mp3");
};


var unReadCommentIdskey = "qquan@comment_newCommentIds";
//保存新的评论ID
function storeUnReadCommentId(paramJson){
	var myId = "";
	var commentId = "";
	if(paramJson){
		myId = paramJson.myId;
		commentId = paramJson.commentId;
		if(!commentId || commentId=="" || commentId =="undefined"){
			return;
		}
	}
	if(!myId || myId=="" || myId =="undefined"){
		myId = userUtil.userId();
	}
	var cacheKey = unReadCommentIdskey+myId;
	var newCommentIdIds = imCache.loadData({key: cacheKey});
	if(newCommentIdIds == null){
		newCommentIdIds = commentId+';';
		imCache.saveData({key: cacheKey, value: newCommentIdIds});
	}else{
		newCommentIdIds = newCommentIdIds.replace(commentId+';','')+commentId+';';
		imCache.saveData({key: cacheKey, value: newCommentIdIds});
	}
}
//去掉已读评论ID
function removeReadedCommentId(paramJson){
	var myId = "";
	var commentId = "";
	if(paramJson){
		myId = paramJson.myId;
		commentId = paramJson.commentId;
		if(!commentId || commentId=="" || commentId =="undefined"){
			return;
		}
	}
	if(!myId || myId=="" || myId =="undefined"){
		myId = userUtil.userId();
	}
	var cacheKey = unReadCommentIdskey+myId;
	var newCommentIdIds = imCache.loadData({key: cacheKey});
	if(newCommentIdIds != null){
		newCommentIdIds = newCommentIdIds.replace(commentId+';','');
		imCache.saveData({key: cacheKey, value: newCommentIdIds});
	}
}

function getUnReadedCommentIds(paramJson){
	if(userUtil.loginToken()===""){
		return "";
	}
	var myId = "";
	if(paramJson){
		myId = paramJson.myId;
	}
	if(!myId || myId=="" || myId =="undefined"){
		myId = userUtil.userId();
	}
	var newCommentIdIds = imCache.loadData({key: unReadCommentIdskey+myId});
	if(newCommentIdIds != null){
		return newCommentIdIds;
	}else{
		return "";
	}
}

function removeHistoryMessage(vsUserId) {
	loadUserByUserId(vsUserId,function(imUser){
		var vsImId = imUser.imId;
		setOurMessageTime({herId:vsImId});//缓存消息的删除时间
		easemob.deleteConversation([vsImId],function(data){
			deviceone.print(JSON.stringify(data),"IM删除会话回调")
		});
	});
}

var ourMessageTimeKey = "qquan@ourmessage_time";
/**
 * 设置我们的聊天消息的删除时间
 * @param paramJson
 * @returns
 */
function setOurMessageTime(paramJson){
	if(userUtil.loginToken()===""){
		return;
	}
	if(paramJson){
		var myId = paramJson.myId;
		var herId = paramJson.herId;
		if(!myId || myId=="" || myId =="undefined"){
			myId = userUtil.userId();
		}
		if(herId!="" && herId!="undefined"){
			var nowTime = new Date().getTime();
			imCache.saveData({key: ourMessageTimeKey+myId+herId, value: nowTime});
		}
	}
};

/**
 * 查询我们的聊天消息的删除时间
 * @param paramJson
 * @returns
 */
function getOurMessageTime(paramJson){
	var nowTime = new Date().getTime();
	if(userUtil.loginToken()===""){
		return nowTime;
	}
	if(paramJson){
		var myId = paramJson.myId;
		var herId = paramJson.herId;
		if(!myId || myId=="" || myId =="undefined"){
			myId = userUtil.userId();
		}
		if(herId!="" && herId!="undefined"){
			var cacheKey = ourMessageTimeKey+myId+herId;
			if(imCache.hasData(cacheKey)){
				var value = imCache.loadData(cacheKey);
				return (!value || value==null || value=="undefined") ? 0 : value;
			}else{
				return nowTime-(1000 * 60 * 60 * 24 * 365);//一年前
			}
		}else{
			return nowTime;
		}
	}else{
		return nowTime;
	}
};

//缓存后台的推送消息
var adminPushMsgCacheKey="im_admin_push_msg";//key
function addAdminPushCahce(title,content,url){
	if(title!=null && content!="undefined"){
		var pushMsgList= imCache.loadData({key: adminPushMsgCacheKey});
		var msgId = new Date().getTime();
		var time = new Date().getTime();
		if(pushMsgList){
			pushMsgList.push({"msgId":msgId,"title":title,"content":content,"url":url,"time":time});
			imCache.saveData({key: adminPushMsgCacheKey, value: pushMsgList});
		}else{
			pushMsgList = [];
			pushMsgList.push({"msgId":msgId,"title":title,"content":content,"url":url,"time":time});
			imCache.saveData({key: adminPushMsgCacheKey, value: pushMsgList});
		}	
	}
}

//查询后台的推送消息列表
function getAdminPushCahce(){
	var pushMsgList= imCache.loadData({key: adminPushMsgCacheKey});
	if(pushMsgList){
		return pushMsgList;
	}else{
		return [];
	}	
}

//从缓存中删除一条推送消息
function removeAdminPushCahce(vsMsgId){
	var pushMsgList= imCache.loadData({key: adminPushMsgCacheKey});
	if(pushMsgList){
		if(pushMsgList.length>0){
			for(var i=0;i<pushMsgList.length;i++){
				if(pushMsgList[i].msgId = vsMsgId){
					pushMsgList.splice(i,1);//删除这条消息
					break;
				}
			}
			imCache.saveData({key: adminPushMsgCacheKey, value: pushMsgList});
		}
		
	}else{
		pushMsgList = [];
		imCache.saveData({key: adminPushMsgCacheKey, value: pushMsgList});
	}
}
//IM登陆与监听
module.exports.initIM = initIM;
module.exports.loginIM = loginIM;
module.exports.addMsgListener = addMsgListener;
//IM进入聊天页面
module.exports.toChat = toChat;
module.exports.toGroupChat = toGroupChat;
//IM用户缓存【我】
module.exports.loadMe = loadMe;
module.exports.reflashCacheMe = reflashCacheMe;
//IM用户缓存【他】
module.exports.loadUserByImId = loadUserByImId;
module.exports.loadUserByUserId = loadUserByUserId;
module.exports.reflashCacheUser = reflashCacheUser;
//IM群组缓存
module.exports.loadGroupByImId = loadGroupByImId;
module.exports.loadGroupByGroupId = loadGroupByGroupId;
module.exports.reflashCacheGroup = reflashCacheGroup;

//IM语音缓存
module.exports.loadAudioFile = loadAudioFile;
module.exports.isUnReadAudio = isUnReadAudio;
module.exports.removeReadedAudioId = removeReadedAudioId;
module.exports.storeUnReadAudioIds = storeUnReadAudioIds;
//新消息提醒
module.exports.alertNewMsg = alertNewMsg;
//指定对话是否静音【消息是否打扰,针对指定的聊天对象】
module.exports.cacheMsgSilence = cacheMsgSilence;
//保存图片
module.exports.downloadImage = downloadImage;
//去圈子成员、群聊成员 列表
module.exports.toGroupMember = toGroupMember;
//播放xiu声音
module.exports.playXiu = playXiu;
//V2-我的未读消息数量【+1】
module.exports.increaseMyUnReadCount = increaseMyUnReadCount;
//V2-我的未读消息数量【减少】
module.exports.reduceMyUnReadCount = reduceMyUnReadCount;
//V2-我的未读消息数量【清零】
module.exports.clearMyUnReadCount = clearMyUnReadCount;
//V2-我的未读消息数量【查询】
module.exports.getMyUnReadCount = getMyUnReadCount;

//V2-我跟她的聊天--未读消息数量+1【针对聊天对象】
module.exports.increaseUnReadCount2Her = increaseUnReadCount2Her;
//V2-我跟她的聊天--未读消息数量【清零】
module.exports.clearUnReadCount2Her = clearUnReadCount2Her;
//V2-我跟她的聊天--未读消息数量【查询】
module.exports.getUnReadCount2Her = getUnReadCount2Her;
//与在线客服聊天
module.exports.chat2OnlineService = chat2OnlineService;
//发送群聊邀请提醒【"XXX"邀请你加入群聊】
module.exports.sendGroupChatTip = sendGroupChatTip;

//获取所有未读消息数量【andriod专用】
module.exports.cacheUnreadMsgCount4Andriod = cacheUnreadMsgCount4Andriod;

//圈商收到-您有新的订单
module.exports.playOrderTip4Seller = playOrderTip4Seller;

//评论推送的id相关
module.exports.storeUnReadCommentId = storeUnReadCommentId;
module.exports.removeReadedCommentId = removeReadedCommentId;
module.exports.getUnReadedCommentIds = getUnReadedCommentIds;
//删除聊天记录
module.exports.removeHistoryMessage = removeHistoryMessage;
//消息删除时间
module.exports.setOurMessageTime = setOurMessageTime;
module.exports.getOurMessageTime = getOurMessageTime;

//后台推送消息的处理
module.exports.addAdminPushCahce = addAdminPushCahce;
module.exports.getAdminPushCahce = getAdminPushCahce;
module.exports.removeAdminPushCahce = removeAdminPushCahce;
